<template>
    <div class="particle-chart-wrapper">
        <Title :title="title"></Title>
        <div ref="particleChart" class="particle-chart-dom"></div>
    </div>
</template>
<script>
import { Column } from '@antv/g2plot';
import { get } from '@/utils/request';
import moment from 'moment';
import Title from './Title.vue';

export default {
    name: 'ParticleChart',
    components: { Title },
    data() {
        return {
            title: '实时PM2.5监测',
            columnChart: null,
            timer: null,
            particleData: [],
            qualityColors: {
                '优': '#22c55e',
                '良': '#eab308',
                '轻度污染': '#f97316',
                '中度污染': '#ef4444',
                '重度污染': '#8b5cf6'
            },
            resizeTimeout: null
        };
    },
    methods: {
        initColumnChart() {
            // 确保容器存在
            if (!this.$refs.particleChart) {
                console.error('❌ 图表容器DOM不存在！');
                return;
            }

            // 确保数据有效
            if (!this.particleData || this.particleData.length === 0) {
                console.warn('⚠️ 数据为空，使用默认数据兜底');
                this.particleData = this.getDefaultData();
            }

            // 销毁旧实例（如果存在）
            this.destroyChart();

            try {
                // 创建新图表实例
                this.columnChart = new Column(this.$refs.particleChart, {
                    data: this.particleData,
                    xField: 'time',
                    yField: 'pm25',
                    xAxis: {
                        label: { style: { fill: "#fff" } },
                        line: { style: { stroke: "#fff" } }
                    },
                    yAxis: {
                        label: { style: { fill: "#fff" } },
                        line: { style: { stroke: "#fff" } },
                        min: 0,
                        max: 150
                    },
                    columnStyle: {
                        fill: ({ quality }) => this.qualityColors[quality] || '#ccc',
                    },
                    tooltip: {
                        fields: ['time', 'pm25', 'quality'],
                        domStyles: {
                            "g2-tooltip": { background: '#147', color: "#fff" }
                        }
                    },
                    interactions: ['element-active']
                });

                this.columnChart.render();
                console.log('✅ 图表渲染成功');
            } catch (error) {
                console.error('❌ 图表初始化失败:', error.message);
                this.columnChart = null; // 初始化失败时重置实例
                this.showFallbackMessage();
            }
        },

        // 单独的图表销毁方法
        destroyChart() {
            if (this.columnChart && typeof this.columnChart.destroy === 'function') {
                this.columnChart.destroy();
            }
            this.columnChart = null;
        },

        getDefaultData() {
            return [
                { time: '08:00', pm25: 22, quality: '优' },
                { time: '08:10', pm25: 36, quality: '良' },
                { time: '08:20', pm25: 58, quality: '良' },
                { time: '08:30', pm25: 79, quality: '轻度污染' },
                { time: '08:40', pm25: 62, quality: '良' },
                { time: '08:50', pm25: 45, quality: '良' },
                { time: '09:00', pm25: 30, quality: '优' },
                { time: '09:10', pm25: 41, quality: '良' }
            ];
        },

        generateMockData() {
            const data = [];
            const now = new Date();
            for (let i = 7; i >= 0; i--) {
                const time = new Date(now.getTime() - i * 10 * 60 * 1000);
                const pm25 = parseFloat((10 + Math.random() * 100).toFixed(1));
                data.push({
                    insert_time: time,
                    pm25: pm25,
                    quality: this.getQualityLevel(pm25)
                });
            }
            return { data: { list: data } };
        },

        getQualityLevel(value) {
            if (value <= 35) return '优';
            if (value <= 75) return '良';
            if (value <= 115) return '轻度污染';
            if (value <= 150) return '中度污染';
            return '重度污染';
        },

        processData(res) {
            this.particleData = res.data.list.map(item => ({
                time: moment(item.insert_time).format("HH:mm"),
                pm25: item.pm25,
                quality: item.quality
            }));
            this.updateChartData();
        },

        updateChartData() {
            // 检查图表实例是否有效
            if (this.columnChart && typeof this.columnChart.changeData === 'function') {
                this.columnChart.changeData(this.particleData);
            } else {
                this.initColumnChart();
            }
        },

        async fetchParticleData() {
            try {
                const mockData = this.generateMockData();
                this.processData(mockData);
            } catch (error) {
                console.error('获取数据失败，使用默认数据:', error);
                this.particleData = this.getDefaultData();
                this.updateChartData();
            }
        },

        // 修复的resize处理方法
        handleResize() {
            // 清除之前的定时器
            if (this.resizeTimeout) {
                clearTimeout(this.resizeTimeout);
            }
            
            // 节流处理
            this.resizeTimeout = setTimeout(() => {
                // 关键：检查图表实例是否存在且resize方法有效
                if (this.columnChart && typeof this.columnChart.resize === 'function') {
                    try {
                        const container = this.$refs.particleChart;
                        const { width, height } = container.getBoundingClientRect();
                        
                        if (width > 0 && height > 0) {
                            this.columnChart.resize({ width, height });
                        }
                    } catch (resizeError) {
                        console.error('图表resize失败:', resizeError.message);
                        // 失败时重新初始化图表
                        this.initColumnChart();
                    }
                }
            }, 500);
        },

        showFallbackMessage() {
            if (this.$refs.particleChart) {
                this.$refs.particleChart.innerHTML = `
                    <div style="color:white; text-align:center; padding:20px;">
                        PM2.5监测数据<br>
                        08:00 - 22μg/m³(优)<br>
                        08:10 - 36μg/m³(良)
                    </div>
                `;
            }
        }
    },

    async mounted() {
        await this.$nextTick();
        this.particleData = this.getDefaultData();
        this.initColumnChart();
        
        setTimeout(() => {
            this.fetchParticleData();
        }, 1000);

        this.timer = setInterval(() => {
            this.fetchParticleData();
        }, 10000);

        window.addEventListener('resize', this.handleResize);
    },

    beforeDestroy() {
        if (this.timer) clearInterval(this.timer);
        if (this.resizeTimeout) clearTimeout(this.resizeTimeout);
        window.removeEventListener('resize', this.handleResize);
        this.destroyChart(); // 使用专门的销毁方法
    }
};
</script>
<style lang="less" scoped>
.particle-chart-wrapper {
    width: 100%;
    max-height: 300px;
    min-height: 150px;
    box-sizing: border-box;
    padding: 5px;
    color: white;
    overflow: hidden;
}

.particle-chart-dom {
    width: 100%;
    height: 200px;
    box-sizing: border-box;
}
</style>
    